<style scoped>

</style>

<template>
  <div class="_role-form-con">
    <Card>
      <p slot="title">
        <Icon type="edit"></Icon>
        角色表单
      </p>
      <div slot="extra" style="position:absolute; top: -5px; right: 0;">
        <Button type="primary" :loading="form.loading" icon="checkmark" @click="handleSubmit(form)">
          <span v-if="!form.loading">提交</span>
          <span v-else>提交中</span>
        </Button>
      </div>

      <Row type="flex" justify="center">
        <Col :span="22">
          <Form :model="form" label-position="top">
            <FormItem label="角色名称">
              <Input v-model="form.name" placeholder="请输入角色名称"/>
            </FormItem>
            <FormItem label="角色标识">
              <Input v-model="form.identifier" placeholder="请输入角色标识(英文)"/>
            </FormItem>
            <FormItem label="角色可使用功能">
              <Tree :data="treeData" @on-check-change="handleCheckChange" show-checkbox></Tree>
            </FormItem>
          </Form>
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script>
  export default {
    name: "RoleForm",
    props: ['treeData'],
    data() {
      return {
        form: {
          name: '',
          identifier: '',
          functions: [],
          loading: false
        }
      }
    },
    methods: {
      handleCheckChange(checkArr) {
        this.form.functions = []
        checkArr.forEach(ele => {
          if (ele.function) {
            this.form.functions.push(ele.function.id)
          }
        })
      },
      handleSubmit(form) {
        this.form.loading = true;
        let formData = {
          name: form.name,
          identifier: form.identifier,
          functions: form.functions
        }

        this.$emit('on-submit', formData, (status) => {
          if (status) {
            Object.assign(this.$data.form, this.$options.data().form)
          }
          this.form.loading = false;
        })
      }
    }
  }
</script>
